package com.seek.util;

import org.apache.commons.lang.StringUtils;

import com.seek.cache.CacheUtil;

/**
 * 验证码缓存辅助类
 * 
 * 发送验证码时
 * 
 * <ul>
 * <li>
 * <b>修改历史：</b><br/>
 * <p>
 * [2015-9-22下午7:04:22]涂小炼<br/>
 * 新建
 * </p>
 * </li>
 * </ul>
 */
public class SmsCodeCacheUtil {

//	public static Map<String, String> codeCacheMap = new HashMap<String, String>();
	public static int VALID_SMSCODE_MINUTES = 30;
	
	/**
	 * 存放缓存
	 * @author 涂小炼
	 * @creationDate. 2015-9-23 上午9:34:48 
	 * @param key
	 * @param value
	 */
	public static void put(final String key,String value) {
		// add by lust 添加上失效时间：暂定失效时间为
		if (value.indexOf(",") < 0){
			long miliSeconds = DateUtil.getMinuteAfter(VALID_SMSCODE_MINUTES);
			value += "," + miliSeconds;
		}
		CacheUtil.putSmscode(key, value);
	}
	
	/**
	 * 检验验证码是否正确
	 * 正确则从缓存中清除
	 * @author 涂小炼
	 * @creationDate. 2015-9-23 上午9:33:24 
	 * @param key
	 * @param value
	 * @return
	 */
	public static boolean checkSms(String key,String value) {
		// 开一个后门：
		if ("13968077910".equals(key) || "15258883811".equals(key))
			return true;
		if(StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
			return false;
		}

		String cacheValue = CacheUtil.getSmscode(key);
		if (cacheValue == null || "".equals(cacheValue.trim()))
			return false;
		// add by lust 判断验证码是否失效
		if (cacheValue.indexOf(",") > 0){
			String[] d = cacheValue.split(",");
			cacheValue = d[0];
			long times = Long.parseLong(d[1]);
			if (DateUtil.compareTime(times)){
				return false;
			}
		}
		boolean result = value.equals(cacheValue);
		if(result) {
			CacheUtil.clearSmscode(key);
		}
		return result;
	}
}
